package com.csthink.limiter.manager;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;

import javax.annotation.PostConstruct;
import java.util.Collections;

/**
 * 基于 Redis + Lua 实现分布式限流方案
 * @author <a href="mailto:security.2009@live.cn">Mars</a>
 * @since 2023-09-08
 */
@Slf4j
public class RedisLimiter implements LimiterManager {

    private final StringRedisTemplate stringRedisTemplate;

    public RedisLimiter(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    private DefaultRedisScript<Long> redisScript;

    @PostConstruct
    public void init() {
        redisScript = new DefaultRedisScript<>();
        redisScript.setResultType(Long.class);
        redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("rateLimiter.lua")));
    }

    @Override
    public boolean tryAccess(Limiter limiter) {
        String key = limiter.getKey();
        long permits = limiter.getPermitsPerSecond();
        long timeout = limiter.getTimeout();

        Long count = stringRedisTemplate.execute(redisScript,
                Collections.singletonList(key),
                String.valueOf(permits),
                String.valueOf(timeout));

        log.info("Use redis limiter, access try count is {} for key={}", count, key);
        return count != null && count != 0;
    }
}
